#!/bin/bash

# DataWorks 数据中台 - 构建和运行脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 函数：打印彩色信息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 函数：检查Docker是否安装
check_docker() {
    if ! command -v docker &> /dev/null; then
        print_error "Docker 未安装，请先安装 Docker"
        exit 1
    fi

    if ! command -v docker-compose &> /dev/null; then
        print_error "Docker Compose 未安装，请先安装 Docker Compose"
        exit 1
    fi
}

# 函数：构建前端镜像
build_frontend() {
    print_info "开始构建前端镜像..."
    cd frontend
    docker build -t dataworks-frontend:latest .
    cd ..
    print_success "前端镜像构建完成"
}

# 函数：构建后端镜像
build_backend() {
    print_info "开始构建后端镜像..."
    docker build -t dataworks-backend:latest .
    print_success "后端镜像构建完成"
}

# 函数：构建所有镜像
build_all() {
    print_info "开始构建所有镜像..."
    docker-compose build
    print_success "所有镜像构建完成"
}

# 函数：启动服务
start_services() {
    print_info "启动所有服务..."
    docker-compose up -d
    
    print_info "等待服务启动..."
    sleep 10
    
    # 检查服务状态
    print_info "检查服务状态:"
    docker-compose ps
    
    print_success "服务启动完成!"
    print_info "访问地址:"
    echo "  前端界面: http://localhost:3000"
    echo "  后端API:  http://localhost:8000"
    echo "  Airflow:  http://localhost:8080"
    echo "  Doris FE: http://localhost:8030"
}

# 函数：停止服务
stop_services() {
    print_info "停止所有服务..."
    docker-compose down
    print_success "服务已停止"
}

# 函数：重启服务
restart_services() {
    print_info "重启所有服务..."
    docker-compose down
    docker-compose up -d
    print_success "服务重启完成"
}

# 函数：查看日志
view_logs() {
    local service=$1
    if [ -z "$service" ]; then
        print_info "查看所有服务日志..."
        docker-compose logs -f
    else
        print_info "查看 $service 服务日志..."
        docker-compose logs -f "$service"
    fi
}

# 函数：清理资源
cleanup() {
    print_warning "这将删除所有容器、镜像和数据卷，确认继续？ (y/N)"
    read -r response
    if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
        print_info "清理 Docker 资源..."
        docker-compose down -v
        docker system prune -f
        print_success "清理完成"
    else
        print_info "取消清理操作"
    fi
}

# 函数：健康检查
health_check() {
    print_info "执行健康检查..."
    
    services=("dataworks-frontend" "dataworks-backend" "dataworks-postgres" "dataworks-redis")
    
    for service in "${services[@]}"; do
        if docker-compose ps | grep -q "$service.*Up"; then
            print_success "$service: 运行正常"
        else
            print_error "$service: 未运行或异常"
        fi
    done
}

# 函数：显示帮助
show_help() {
    echo "DataWorks 数据中台 - 构建和运行脚本"
    echo ""
    echo "用法: $0 [命令]"
    echo ""
    echo "命令:"
    echo "  build-frontend    构建前端镜像"
    echo "  build-backend     构建后端镜像"
    echo "  build-all         构建所有镜像"
    echo "  start             启动所有服务"
    echo "  stop              停止所有服务"
    echo "  restart           重启所有服务"
    echo "  logs [service]    查看日志（可指定服务名）"
    echo "  status            查看服务状态"
    echo "  health            健康检查"
    echo "  cleanup           清理所有资源"
    echo "  help              显示帮助"
    echo ""
    echo "示例:"
    echo "  $0 build-all && $0 start"
    echo "  $0 logs dataworks-frontend"
    echo "  $0 health"
}

# 主逻辑
main() {
    check_docker
    
    case "${1:-help}" in
        "build-frontend")
            build_frontend
            ;;
        "build-backend")
            build_backend
            ;;
        "build-all")
            build_all
            ;;
        "start")
            start_services
            ;;
        "stop")
            stop_services
            ;;
        "restart")
            restart_services
            ;;
        "logs")
            view_logs "$2"
            ;;
        "status")
            docker-compose ps
            ;;
        "health")
            health_check
            ;;
        "cleanup")
            cleanup
            ;;
        "help"|*)
            show_help
            ;;
    esac
}

# 执行主函数
main "$@" 